#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
python 操作RabbitMQ,采用自定义exchange，并指定exchange类型为direct
"""

__author__ = 'hubert'


import pika
import time

# host
host = '127.0.0.1'
# port
port = 5672
# name
username = 'test'
# password
password = 'test'
# vhost
virtualHost = 'test_vhosts'

# 生产者,采用自定义exchange，为direct类型，通过指定队列名称(如:Python)的方式写入或获取消息，此时设置routingkey无效
def producer_direct():
    # 设置用户密码
    credentials = pika.PlainCredentials(username, password)
    # 设置IP、端口、vhost信息
    connection = pika.BlockingConnection(pika.ConnectionParameters(host, port, virtualHost, credentials))
    # 创建频道
    channel = connection.channel()
    # 创建exchange(交换机),并设定类型为direct，同时设置持久化
    channel.exchange_declare(exchange='log_info_direct', exchange_type='direct', durable=True)

    # 若在MQ管理后端创建与exchange对应的queue及绑定关系，则下面代码不需要，作用为自动创建queue并与exchange绑定
    # channel.queue_declare(queue='Python_info', durable=True)
    # 绑定queue与exchange，若不绑定，消息不能写入queue
    # channel.queue_bind(queue='Python_info', exchange='log_info')

    """
    # 1.不指定exchange，表示采用默认exchange，
    # 2.默认的Exchange隐式绑定到每个队列，路由键等于队列名称。无法与默认交换机显式绑定或解除绑定。它也不能被删除。
    # 3.body是要插入的内容
   """

    length = 10
    # delivery_mode=2 消息持久化
    properties = pika.BasicProperties(delivery_mode=2)
    for index in range(length):
        body = 'Python_direct' + str(index + 1)
        # 设置exchange与routing_key,direct类型的key值不能为空
        pub = channel.basic_publish(exchange='log_info_direct', routing_key='key_direct', body=body, properties=properties)
        if pub:
            print('发送成功', str(index + 1))
        else:
            print('发送失败', str(index + 1))
    print("----发送消息完毕---")
    # 关闭链接
    connection.close()

# 定义一个回调函数来处理，这边的回调函数就是将信息打印出来。
def callback(channel, method, properties, body):
    print(" [x] Received %r" % body.decode('utf-8'))
    # 时间间隔为秒
    time.sleep(3)
    # 确认回执
    channel.basic_ack(delivery_tag=method.delivery_tag)


def customer_direct():
    # 设置用户密码
    credentials = pika.PlainCredentials(username, password)
    # 设置IP、端口、vhost信息
    connection = pika.BlockingConnection(pika.ConnectionParameters(host, port, virtualHost, credentials))
    # 创建频道
    channel = connection.channel()
    # 设置exchange，交换机类型，持久化
    channel.exchange_declare(exchange='log_info_direct', exchange_type='direct', durable=True)
    # 设置队列，持久化
    channel.queue_declare(queue='Python_info_direct', durable=True)
    # 绑定队列与exchange，若设置key为空，则会重新绑定key到队列何exchange上
    channel.queue_bind(queue='Python_info_direct', exchange='log_info_direct', routing_key='key_direct')
    # 关闭自动删除 no_ack=False
    channel.basic_consume(callback, queue='Python_info_direct', no_ack=False)

    channel.start_consuming()


if __name__ == '__main__':
    print('MQ direct')
    # producer_direct()
    customer_direct()
